/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import javax.servlet.http.HttpServletRequest;
import nl.captcha.Captcha;
import org.apache.log4j.Logger;

/**
 * Validate that an input parameter matches a CAPTCHA string
 */
public class CaptchaValidator implements IValidator {

    Logger log = Logger.getLogger(this.getClass());

    private String errorMessage = "Invalid access code entered."; 

    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	if (!(obj instanceof String)) throw new AppException(errorMessage);

	String output   = (String)obj;
	Captcha captcha = (Captcha)request.getSession().getAttribute(Captcha.NAME);

	if (!captcha.isCorrect(output)) throw new AppException(errorMessage);

	return output;
    }

    /*
     * Uncomment to use old-style CAPTCHA 
    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	if (!(obj instanceof String)) throw new AppException(errorMessage);

	String captcha    = (String)obj;
	String captchaKey = (String)request.getSession().getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY);

	log.debug("CAPTCHA KEY: " + captchaKey);

	if (Utils.isEmpty(captcha) || !captcha.equalsIgnoreCase(captchaKey)) throw new AppException(errorMessage);

	return captcha;
    }
    */

}
